var modes = {
  NONE: 0,
  ACUTE: 1,
  GRAVE: 2
};

var mode = modes.NONE;

var keys = {
  LOWER_A: 97,
  LOWER_E: 101,
  GRAVE_ACCENT: 192,
  APOSTROPHE: 222,
  LOWER_GRAVE_A: 224,
  LOWER_ACUTE_A: 225,
  LOWER_GRAVE_E: 232,
  LOWER_ACUTE_E: 233
};

var acute_map = {};
acute_map[keys.LOWER_A] = keys.LOWER_ACUTE_A;
acute_map[keys.LOWER_E] = keys.LOWER_ACUTE_E;

var grave_map = {};
grave_map[keys.LOWER_A] = keys.LOWER_GRAVE_A;
grave_map[keys.LOWER_E] = keys.LOWER_GRAVE_E;

var mode_map = {};
mode_map[modes.ACUTE] = acute_map;
mode_map[modes.GRAVE] = grave_map;

document.addEventListener('keydown', function(event) {
  if (mode == modes.NONE) {
    if (event.ctrlKey) {
      if (event.keyCode == keys.APOSTROPHE) {
        mode = modes.ACUTE;
      } else if (event.keyCode == keys.GRAVE_ACCENT) {
        mode = modes.GRAVE;
      }
    }
  }
});

document.addEventListener('keypress', function(event) {
  if (mode == modes.NONE)
    return;

  var key_map = mode_map[mode];
  if (event.keyCode in key_map) {
    mode = modes.NONE;
    event.preventDefault();
    event.stopPropagation();
 
    if (event.target.value !== undefined) {
      event.target.value += String.fromCharCode(key_map[event.keyCode]);
    }
  }
});
